import { useRef, useState } from 'react'
import { MessageType } from '@/types'
import clsx from 'clsx'
import { useAtomValue } from 'jotai'
import { isToday, isThisYear, format } from 'date-fns'
import Markdown from '@/components/Pannel/Markdown'
import {
  showMessageTimestampAtom, showModelNameAtom,
  showTokenCountAtom, showWordCountAtom,
} from '@/atoms'
import { Box, Avatar } from '@mui/material'
import { countWord, copyText } from '@/funcs/utils'
import { estimateTokensFromMessages } from '@/funcs/models/token'
import { useTranslation } from 'react-i18next'
import useChat from '@/hooks/useChat'
import useMessage from '@/hooks/useMessage'
import { showEditMessageDialog } from '@/components/Dialogs/EditMessage'
import { showAlertDialog } from '@/components/Base/Alert'

export default function Message({ msg }: { msg: MessageType }) {
  const { t } = useTranslation()
  const ref = useRef<HTMLDivElement>(null)
  const tips: string[] = []
  const showMessageTimestamp = useAtomValue(showMessageTimestampAtom)
  const showModelName = useAtomValue(showModelNameAtom)
  const showTokenCount = useAtomValue(showTokenCountAtom)
  const showWordCount = useAtomValue(showWordCountAtom)
  const { getResMessage } = useChat()
  const { deleteMessage, sliceMessage } = useMessage()

  if (showWordCount) {
    tips.push(`words: ${countWord(msg.content)}`)
  }
  if (showTokenCount) {
    tips.push(`token count: ${estimateTokensFromMessages([msg])}`)
  }

  if (showModelName && msg.role === 'assistant') {
    tips.push(`model: ${msg.model || 'unknown'}`)
  }

  if (showMessageTimestamp && msg.timestamp !== undefined) {
    const date = new Date(msg.timestamp)
    let messageTimestamp: string
    if (isToday(date)) {
      messageTimestamp = format(date, 'HH:mm')
    }
    else if (isThisYear(date)) {
      messageTimestamp = format(date, 'MM-dd HH:mm')
    }
    else {
      messageTimestamp = format(date, 'yyyy-MM-dd HH:mm')
    }

    tips.push('time: ' + messageTimestamp)
  }

  const [copied, setCopied] = useState(false)

  const copyHandle = () => {
    const res = copyText(msg.content)
    if (res) {
      setCopied(true)
      setTimeout(() => {
        setCopied(false)
      }, 3000)
    }
  }
  const deleteHandle = () => {
    showAlertDialog({
      title: t('delete message'),
      content: t('are you sure to delete'),
      onOk: () => {
        deleteMessage(msg.id)
      },
    })
  }
  const editHandel = () => {
    showEditMessageDialog(msg)
  }

  const reAskHandle = () => {
    sliceMessage(msg.id)
    getResMessage()
  }

  return (
    <Box
      ref={ref}
      key={msg.id}
      className="my-5"
    >
      <div className="flex flex-nowrap gap-2">
        <Avatar sx={{
          width: 34,
          height: 34,
          bgcolor: 'transparent',
          boxShadow: '0 0 0 2px rgba(200,200,200,0.4)',
        }}
        >
          <Box className={clsx('w-[26px] text-gray-400', {
            'i-material-symbols:camera-rounded': msg.role == 'assistant',
            'i-material-symbols:person-rounded': msg.role == 'user',
            'i-material-symbols:deployed-code': msg.role == 'system',
          })}
          >
          </Box>
        </Avatar>
        <div className="group flex flex-1 flex-col overflow-hidden">
          <Box className="w-full flex">
            {
              msg.role == 'assistant'
                ? (
                    <Markdown>
                      {msg.content}
                    </Markdown>
                  )
                : (
                    <div className="max-w-4/7 w-auto overflow-auto whitespace-pre-wrap rounded-lg bg-gray-100 p-0.4rem leading-1.7rem dark:bg-#2f2f2f">
                      {msg.content}
                    </div>
                  )
            }

          </Box>
          <div className="px-0.4rem text-0.8rem opacity-50">
            {tips.join(', ')}
          </div>
          <div className="flex gap-2 p-0.4rem opacity-0 *:cursor-pointer group-hover:opacity-70">
            {
              copied
                ? <div className="i-material-symbols:check" />
                : <div onClick={copyHandle} className="i-material-symbols:content-copy-outline" />
            }
            <div onClick={deleteHandle} className="i-material-symbols:delete-outline-rounded" />
            <div onClick={editHandel} className="i-material-symbols:edit-square-outline" />
            {
              msg.role === 'user'
              && (<div onClick={reAskHandle} className="i-material-symbols:refresh-rounded" />)
            }
          </div>
        </div>
      </div>
    </Box>
  )
}
